# -*- coding:utf-8 -*-
# Create your views here.
from bookmarks.models import Term, SearchResult, Pattern, Type, Keyword
from django.contrib.auth import logout
from django.contrib.auth.models import User
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
import httplib
import json
import string
import urllib
# host = "70.121.43.108:8080" #when use VDI server
host = "70.8.51.26:8080"  # rest server 
basicUrl = "/MES_RestService/mes/"

def json_page(request, path):
    conn = httplib.HTTPConnection(host)
    conn.request("GET", basicUrl + path)
    response = conn.getresponse()
    jsonData = response.read()
    variables = RequestContext(request, {
            'json' : jsonData,
                         })
    return render_to_response('json.html' , variables)
def visualviser_page(request):
    query = request.GET.get('query')
    if query is None or query == '':
        print 'no query'
        return render_to_response('visualviser.html', None)
    else :
        filteredquery = urllib.quote(query.encode('utf8'), '/:')
        url = basicUrl + "search/get/q=" + filteredquery
        data = get_json(host, url)
        resultList = []
        if data is None :
            resultList.append(SearchResult("Your search \"" + query + "\" did not match any documents. ", -1, "", "", ""))
            size = 0
        else :
            for d in data["restSearchResultVO"]:
                if d == 'content' :  # if search result is only one, 
                    d = data["restSearchResultVO"]
#                    array = string.split(d['category'], " ", 2);
                    array = d['category'];
                    result = SearchResult(d['title'], d["date"], d['content'], make_summary(d['content'], query), array) 
                    resultList.append(result)
                    break
#                array = string.split(d['category'], " ", 2);
                array = d['category'];
                result = SearchResult(d['title'], d["date"], d['content'], make_summary(d['content'], query), array) 
                print array
                resultList.append(result)
            size = len(resultList)
        variables = RequestContext(request , {   'result' : resultList,
                                                 'query' : query,
                                                 'size' : size})
        
        return render_to_response('visualviser.html', variables)    
def d3force_page(request):
    return render_to_response('d3force.html', RequestContext(request))
def d3cloud_page(request):
    return render_to_response('d3cloud.html', RequestContext(request))
def d3cooccur_page(request):
    return render_to_response(
                'd3coocurrence.html' , RequestContext(request)
    )
def main_page(request):
    return render_to_response(
                'main_page.html' , RequestContext(request)
    )

def user_page(request, username):
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404('Requested user not found')
    bookmarks = user.bookmark_set.all()
    variables = RequestContext(request, {
            'username' : username,
            'bookmarks' : bookmarks ,
                         })
    return render_to_response('user_page.html', variables)
def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')
def dictionary_page(request):
    data = get_json(host, basicUrl + "dic/get")
    termList = []
    for d in data["restTermVO"]:
        result = Term(d["term_id"], d["term"], d["synonym_group_id"], d["term_type"], d["term_description"])
        termList.append(result)
    data2 = get_json(host, basicUrl + "termType/get")
    patternList = []
    for d in data2["restTypeVO"] :
        result = Type(d["type_id"], d["type_name"], d["type_description"])
        patternList.append(result)
        
    variables = RequestContext(request , {
                              'termList' : termList ,
                              'patternList' : patternList
                                })
    return render_to_response('dictionary.html', variables)

def keyword_page(request):
    data = get_json(host, basicUrl + "keyword/get")
    keywordList = []
    for d in data["restKeywordVO"]:
        result = Keyword(d["keyword"], d["frequency"])
        keywordList.append(result)
    variables = RequestContext(request , {
                              'keywordList1' : keywordList[0:99] ,
                              'keywordList2' : keywordList[100:199] ,
                              'keywordList3' : keywordList[200:299] ,
                                })
    return render_to_response('keywords.html', variables)

def category_page(request):
    return get_pattern_datas("Category", basicUrl + "categoryPattern/get", basicUrl + "categoryPatternType/get", request)
def ner_page(request):
    return get_pattern_datas("NER", basicUrl + "nerPattern/get", basicUrl + "nerPatternType/get", request)
def search_page(request):
    query = request.GET.get('query')
    if query is None or query == '':
        print 'no query'
        return render_to_response('search.html', None)
    else :
        filteredquery = urllib.quote(query.encode('utf8'), '/:')
        url = basicUrl + "search/get/q=" + filteredquery
        data = get_json(host, url)
        resultList = []
        if data is None :
            resultList.append(SearchResult("Your search \"" + query + "\" did not match any documents. ", -1, "", "", ""))
            size = 0
        else :
            for d in data["restSearchResultVO"]:
                if d == 'content' :  # if search result is only one, 
                    d = data["restSearchResultVO"]
#                    array = string.split(d['category'], " ", 2);
                    array = d['category'];
                    result = SearchResult(d['title'], d["date"], d['content'], make_summary(d['content'], query), array) 
                    resultList.append(result)
                    break
#                array = string.split(d['category'], " ", 2);
                array = d['category'];
                result = SearchResult(d['title'], d["date"], d['content'], make_summary(d['content'], query), array) 
                resultList.append(result)
            size = len(resultList)
        variables = RequestContext(request , {   'result' : resultList,
                                                 'query' : query,
                                                 'size' : size})
        
        return render_to_response('search.html', variables)
def json_line(request, grpParam):       
#    try:
#        query = chartTypeList
#    except ValueError:
#        raise Http404()        
#    query2 = urllib.quote(query.encode('utf8'), '/:')
    url = '/MES_RestService/mes/termFreq/get/group=' + grpParam    
    data = get_json(host, url)
    data_list = []
    query_list = []
    
    
    dic = dict()
    if data is None :
        data_list.append('')
    else :
        for d1 in data['restGroupTF']:            
            query_list.append(d1['query'])
            if(isinstance(d1['list'] , list)) :                         
                for d2 in d1['list'] :                                                   
                    dic[''.join(d2['timeStamp'])] = []
                    dic[''.join(d2['timeStamp'])].append(d2['timeStamp'])
            else :
                dic[''.join(d1['list']['timeStamp'])] = []
                dic[''.join(d1['list']['timeStamp'])].append(d1['list']['timeStamp'])                         
    unit_size = 2;                    
    if data is None :
        data_list.append('')
    else :
        for d1 in data['restGroupTF']:   
            if(isinstance(d1['list'] , list)) :                                              
                for d2 in d1['list'] :                
                    dic[''.join(d2['timeStamp'])].append(int(d2['frequency']))                        
                for k1 in dic.iterkeys():                
                    if(len(dic[k1]) < unit_size) :
                        dic[k1].append(0)                
            else :
                dic[''.join(d1['list']['timeStamp'])].append(int(d1['list']['frequency']))
                for k1 in dic.iterkeys():   
                    if(len(dic[k1]) < unit_size) :
                            dic[k1].append(0)
            unit_size = unit_size + 1           
    dickeys = dic.keys()
    dickeys.sort()       
    for k1 in dickeys:    
        data_list.append(dic[k1])
    json_result = json.dumps({"data_list" : data_list , "query_list" : query_list})
    variables = RequestContext(request , { 'json' : json_result , })
    return render_to_response('json_line.html', variables)     
       
def make_summary(content, query):
    array = content.split('.');
    for line in array:
        if query in line:
            line = string.replace(line, query, '<strong>' + query + '</strong>', 10)
            return line
    return array[0]


def trend_page(request):
    query = request.GET.get('query')
    if query is None or query == '':
        print 'no query'
        return render_to_response('trend.html', None)
    else :
        query2 = urllib.quote(query.encode('utf8'), '/:')
        url = '/MES_RestService/mes/termFreq/get/query=' + query2
        data = get_json(host, url)
        str_list = []
        str_list.append('[')
        if data is None :
            str_list.append('')
        else :
            for d in data['restTermFreqVO']:
                if(d == 'timeStamp') :  # when restTermFreqVO `s size is 1
                    d = data['restTermFreqVO']
                    string = '[\'20120101\',0],'
                    str_list.append(string)
                    string = '[\'' + d['timeStamp'] + '\',' + d['frequency'] + ']' + ','
                    str_list.append(string)
                    break;
                string = '[\'' + d['timeStamp'] + '\',' + d['frequency'] + ']' + ','
                str_list.append(string)
        str_list.append(']')
        result = ''.join(str_list)
        variables = RequestContext(request , { 'result' : result , 'name' : query})
        return render_to_response('trend.html', variables)
def tf_page(request):
    variables = RequestContext(request , {   })
    return render_to_response('termfreq.html', variables)
def get_json(host, url):
    conn = httplib.HTTPConnection(host)
    conn.request("GET", url)
    response = conn.getresponse()
    jsonData = response.read()
    data = json.loads(jsonData)
    return data
def get_pattern_datas(name, patternUrl, typeUrl, request):
    patternData = get_json(host, patternUrl)
    print patternData
    patternList = []
    for d in patternData["restPatternVO"]:
        result = Pattern(d["pattern_type_name"], d["pattern_string"])
        patternList.append(result)
    patternTypeData = get_json(host, typeUrl)
    patternTypeList = []
    for d in patternTypeData["restTypeVO"] :
        result = Type(d["type_id"], d["type_name"], d["type_description"])
        patternTypeList.append(result)
    variables = RequestContext(request , {
                              'patternList' : patternList  ,
                              'typeList' : patternTypeList ,
                              'name' : name
                                })
    return render_to_response('pattern.html', variables)


